<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    showFooter
    :title="getTitle"
    width="50%"
    @ok="handleSubmit"
  >
    <Form :model="formData" :label-col="labelCol" :wrapper-col="wrapperCol"
          label-align="right" ref="formRef">
      <div v-for="(item,index) in formSchema">
        <FormItem v-bind="item" v-if="item.component" :name="item.field">

          <Input v-if="item.component==='Input'" :placeholder="'请输入'+item.label"
                 v-model:value="formData[item.field]"></Input>
          <Ainput v-if="item.component==='Ainput'" v-model:value="formData[item.field]"
                  :name="item.field" @success="userSelectSuccessFn"></Ainput>
          <ApiSelect v-if="item.component==='ApiSelect'" :placeholder="'请选择'+item.label"
                     v-bind="item.componentProps"
                     v-model:value="formData[item.field]"></ApiSelect>
        </FormItem>
      </div>
    </Form>

  </BasicModal>
</template>
<script lang="ts" setup>
import {ref, computed, unref, toRaw} from 'vue';
import {BasicForm, useForm} from '@/components/Form';
import {formSchema} from './role.data';
import {BasicModal, useModalInner} from '@/components/Modal';
import {BasicTree, TreeItem} from '@/components/Tree';
import {saveUserRewardsApi, userRewardsDetailApi} from '@/api/sys/rewards';
import Ainput from "@/views/bookManage/components/account/Ainput.vue";
import {Form, FormItem, Input, InputNumber, DatePicker, Select, Switch} from 'ant-design-vue';
import {ApiSelect} from '@/components/Form';

import {useMessage} from "@/hooks/web/useMessage";

const emit = defineEmits(['success', 'register']);
const isUpdate = ref(true);
const treeData = ref<TreeItem[]>([]);
const {createMessage} = useMessage();

const formData = ref({})
const labelCol = ref({span: 3});
const wrapperCol = ref({span: 18});
const formRef = ref();

const userRewardsId = ref("");
const [registerForm, {resetFields, setFieldsValue, validate}] = useForm({
  labelWidth: 90,
  baseColProps: {span: 24},
  schemas: formSchema,
  showActionButtonGroup: false,
});

const [register, {setModalProps, closeModal}] = useModalInner(async (data) => {
  //打开弹层后的回调
  // resetFields();
  setModalProps({confirmLoading: false});
  // 需要在setFieldsValue之前先填充treeData，否则Tree组件可能会报key not exist警告
  // if (unref(treeData).length === 0) {
  //   treeData.value = (await getMenuList()) as any as TreeItem[];
  // }
  isUpdate.value = !!data?.isUpdate;
  userRewardsId.value = "";
  if (unref(isUpdate)) {

    console.log("---data.record:", data.record)
    userRewardsId.value = data.record.userRewardsId;
    let json = {
      userRewardsId: userRewardsId.value
    }
    // if(!data.record.levelName){
    //   data.record.levelName
    // }
    // setFieldsValue(data.record);

    userRewardsDetailApi(json).then((res) => {
      //  console.log("---res::",res)
      if (res.code == 200) {
        let item = res.data;
        if (item) {
          formData.value = item;
          // setFieldsValue(item);
        }

      } else {
        createMessage.error(res.message);

      }
    })

  } else {
    formData.value = {};
  }
});

const getTitle = computed(() => (!unref(isUpdate) ? '新增班级' : '编辑班级'));

async function handleSubmit() {
  try {

    formRef.value
      .validate()
      .then(() => {
        let values = toRaw(formData.value);
        setModalProps({confirmLoading: true});
        // TODO custom api
        values.userRewardsId = userRewardsId.value;
        //保存
        saveUserRewardsApi(values).then((res) => {
          // console.log("---res::",res)
          if (res.code == 200) {
            createMessage.success(res.message);
          } else {
            createMessage.error(res.message);
          }
        })
          .catch((res) => {
            createMessage.error(res.message);
          })
          .finally(() => {
            closeModal();
            emit('success');
          });

      }).catch((error) => {
      console.log('error', error);
    });


  } finally {
    setModalProps({confirmLoading: false});
  }
}

function userSelectSuccessFn(e) {

  formData.value.userId = e.ids;
  formData.value.userName = e.names;
  formRef.value.clearValidate();

}


</script>
